package com.opc.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.opc.Common.Code;
import com.opc.Common.MessageConstant;
import com.opc.Common.Result;
import com.opc.Config.CacheUtil;
import com.opc.Mapper.*;
import com.opc.Pojo.*;
import com.opc.Service.CarService;
import com.opc.Service.CarStatusService;
import com.opc.Service.ScrewService;
import com.opc.Service.WorkingPositionService;
import com.opc.properties.FrequencyProperties;
import com.opc.websocket.WebSocketServer;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Transactional;
//import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.io.ByteArrayOutputStream;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@Slf4j
@RequestMapping("/Car")
public class CarController {

    @Autowired
    private ScrewService screwService;
    @Autowired
    private FrequencyProperties frequencyProperties;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private ScrewTypeMapper screwTypeMapper;
    @Autowired
    private CarService carService;
    @Autowired
    private TorqueStandardsMapper torqueStandardsMapper;
    @Autowired
    private ScrewMapper screwMapper;
    @Autowired
    private CarStatusService carStatusService;
    @Autowired
    private CarNumPrefixMapper carNumPrefixMapper;
    @Autowired
    private CarStatusMapper carStatusMapper;
    @Value("${jwt.path}")
    private String SECRET_KEY;
    @Autowired
    private WorkingPositionMapper workingPositionMapper;
//    @Qualifier("workingPositionService")//为什么会导致启动不了
    @Autowired
    private WorkingPositionService workingPositionService;
    @Autowired
    private CarMapper carMapper;

//    @GetMapping("/sendCarNumPrefix")
//    @Transactional
//    @CrossOrigin
//    public Result sendCarNumPrefix(@RequestHeader("Authorization") String Token,
//                                   @RequestParam(required = false) String CarNumPre) {
//        // 验证令牌
//        if (!isValidToken(Token)) {
//            return new Result(Code.LOGIN_ERR, "无效或过期的令牌");
//        }
//
//        LocalDate today = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String todayStr = today.format(formatter);
//
//        LocalDate yesterday = today.minusDays(1);
//        String yesterdayStr = yesterday.format(formatter);
//
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(CarNumPrefix::getCreateTime, todayStr);
//        int count = carNumPrefixMapper.selectCount(queryWrapper);
//        if (count == 1) {
//            if(CarNumPre != null && !CarNumPre.isEmpty()) {
//                CarNumPrefix carNumPrefix = carNumPrefixMapper.selectOne(queryWrapper);
//                carNumPrefix.setCarNum(CarNumPre);
//                carNumPrefixMapper.updateById(carNumPrefix);
//                return new Result(Code.SAVE_ERR, "今天的车身号前缀已更新");
//            }
//        } else if (count > 1) {
//            log.info("数据库存在多个车身号前缀");
//            return new Result(Code.SAVE_ERR, "存在多个车身号前缀，请联系管理员");
//        }
//
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper0 = new LambdaQueryWrapper<>();
//        queryWrapper0.like(CarNumPrefix::getCreateTime, todayStr);
//        int count0 = carNumPrefixMapper.selectCount(queryWrapper);
//        if (count0 > 0) {
//             return new Result(Code.SAVE_ERR, "今天的车身号前缀已设置");
//        }
//
//        //System.out.println("CarNumPre是:"+CarNumPre);
//        CarNumPrefix carNumPrefix = new CarNumPrefix();
//        if(CarNumPre != null && !CarNumPre.isEmpty()) {
//            //System.out.println("CarNumPre.size()是"+CarNumPre.length());
//            carNumPrefix.setCarNum(CarNumPre);
//        }else {
//            LambdaQueryWrapper<CarNumPrefix> queryWrapperYes = new LambdaQueryWrapper<>();
//            queryWrapperYes.like(CarNumPrefix::getCreateTime, yesterdayStr);
//            int count1 = carNumPrefixMapper.selectCount(queryWrapperYes);
//            CarNumPrefix carNumPrefix0 = null;
//            if (count1 == 1) {
//                carNumPrefix0 = carNumPrefixMapper.selectOne(queryWrapperYes);
//            }else if (count1 > 1) {
//                log.info("存在多个车身号前缀");
//                return new Result(Code.SAVE_ERR, "存在多个车身号前缀，请联系管理员");
//            }
//            if (carNumPrefix0 != null) {
//                carNumPrefix.setCarNum(carNumPrefix0.getCarNum());
//            }
//            carNumPrefix.setCreateTime(new Date());
//            carNumPrefixMapper.insert(carNumPrefix);
//            return new Result(Code.SAVE_OK, "继续使用昨天的车身号前缀");
//        }
//        //count == 0时添加
//        carNumPrefix.setCreateTime(new Date());
//        carNumPrefixMapper.insert(carNumPrefix);
//        return new Result(Code.SAVE_OK, "车身号前缀设置成功");
//    }

    //优化后
    @GetMapping("/getCarNumPrefix")
    @CrossOrigin
    public Result getCarNumPrefix(@RequestParam(required = false) String workingPositionId) {
        // 1. 参数校验（避免空查询或无效参数）
        if (workingPositionId == null || workingPositionId.isEmpty()) {
            return new Result(Code.SAVE_ERR, "工位ID不能为空");
        }

//        // 2. 日期范围查询（替代like，利用索引提高效率）
//        LocalDate today = LocalDate.now();
//        // 当天00:00:00
//        Date todayStart = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
//        // 次日00:00:00（即当天23:59:59的下一秒）
//        Date tomorrowStart = Date.from(today.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());

        // 3. 一次查询获取结果（避免先count再selectOne的两次数据库交互）
        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, workingPositionId);
//                .ge(CarNumPrefix::getCreateTime, todayStart)  // >= 当天0点
//                .lt(CarNumPrefix::getCreateTime, tomorrowStart);  // < 次日0点（精准匹配当天）

        List<CarNumPrefix> prefixList = carNumPrefixMapper.selectList(queryWrapper);

        // 4. 结果判断（基于列表大小，逻辑更简洁）
        if (prefixList.size() == 1) {
            return new Result(Code.SELECT_OK, prefixList.get(0));
        } else if (prefixList.size() > 1) {
            log.warn("工位[{}]存在多个车身号前缀（数量：{}）", workingPositionId, prefixList.size());
            return new Result(Code.SELECT_ERR, "该工位存在多个车身号前缀，请联系管理员");
        } else {
            log.info("工位[{}]未设置当天车身号前缀", workingPositionId);
            return new Result(Code.SELECT_ERR, "该工位未设置车身号前缀");
        }
    }


    //优化前：
//    @GetMapping("/getCarNumPrefix")
//    @CrossOrigin
//    public Result getCarNumPrefix(@RequestParam String workingPositionId) {
//        LocalDate today = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String todayStr = today.format(formatter);
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, workingPositionId);
//        queryWrapper.like(CarNumPrefix::getCreateTime, todayStr);
//        int count = carNumPrefixMapper.selectCount(queryWrapper);
//        CarNumPrefix carNumPrefix = null;
//        if (count == 1) {
//            carNumPrefix = carNumPrefixMapper.selectOne(queryWrapper);
//            return new Result(Code.SELECT_OK, carNumPrefix);
//        }else if (count > 1) {
//            log.info("数据库存在多个车身号前缀");
//            return new Result(Code.SELECT_ERR, "该工位存在多个车身号前缀，请联系管理员");
//        }else {
//            return new Result(Code.SELECT_ERR, "该工位未设置车身号前缀");
//        }
//
//    }

    //优化后：
    @PostMapping("/sendCarNumPrefix")
    @Transactional
    @CrossOrigin
    public Result sendCarNumPrefix(@RequestHeader("Authorization") String token,
                                   @RequestBody CarNumPre carNumPre) {
        // 1. 验证令牌（提前校验，快速失败）
        if (!isValidToken(token)) {
            return new Result(Code.LOGIN_ERR, "无效或过期的令牌");
        }

        // 2. 校验入参（避免空指针）
        String workingPositionIdStr = carNumPre.getWorkingPositionId();
        if (workingPositionIdStr == null || workingPositionIdStr.isEmpty()) {
            return new Result(Code.SAVE_ERR, "工位ID不能为空");
        }
        Long workingPositionId;
        try {
            workingPositionId = Long.valueOf(workingPositionIdStr);
        } catch (NumberFormatException e) {
            return new Result(Code.SAVE_ERR, "工位ID格式错误");
        }

//        // 3. 日期处理（统一工具类，避免重复创建）
//        LocalDate today = LocalDate.now();
//        LocalDate yesterday = today.minusDays(1);
//        // 转换为数据库日期范围查询（替代like，提高索引利用率）
//        Date todayStart = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
//        Date todayEnd = Date.from(today.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant());
//        Date yesterdayStart = Date.from(yesterday.atStartOfDay(ZoneId.systemDefault()).toInstant());
//        Date yesterdayEnd = Date.from(yesterday.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant());

        // 4. 查询当前工位信息（提前查询，避免后续NPE）
        WorkingPosition workingPosition = workingPositionService.getById(workingPositionId);
        if (workingPosition == null) {
            return new Result(Code.SAVE_ERR, "工位不存在");
        }

        try {
            // 5. 处理今日数据
//            CarNumPrefix todayPrefix = getCarNumPrefix(workingPositionId, todayStart, todayEnd);
            CarNumPrefix todayPrefix = getCarNumPrefix(workingPositionId);

            if (todayPrefix != null) {
                return handleExistingPrefix(carNumPre, todayPrefix, workingPosition);
            }else{
                CarNumPrefix carNumPrefix = new CarNumPrefix();
                carNumPrefix.setWorkingPositionId(workingPositionId);
                carNumPrefix.setCarNum(carNumPre.getCarNumPre());
                carNumPrefix.setCreateTime(new Date());
                carNumPrefixMapper.insert(carNumPrefix);
                return new Result(Code.SAVE_OK, "该工位车身号前缀设置成功");
//                return new Result(Code.SAVE_ERR, "该工位未设置车身号前缀");
            }

            // 6. 今日无数据，查询昨日数据
//            CarNumPrefix yesterdayPrefix = getCarNumPrefix(workingPositionId, yesterdayStart, yesterdayEnd);

//            return handleNonExistingPrefix(carNumPre, workingPositionId, yesterdayPrefix, workingPosition);

        } catch (Exception e) {
            log.error("处理车身号前缀失败", e); // 记录异常详情
            return new Result(Code.SAVE_ERR, "系统异常，请重试");
        }
    }

    /**
     * 查询指定工位、指定日期范围内的车身号前缀（抽取重复查询逻辑）
     */
    private CarNumPrefix getCarNumPrefix(Long workingPositionId) {//, Date startDate, Date endDate
        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, workingPositionId);
//                .between(CarNumPrefix::getCreateTime, startDate, endDate); // 日期范围查询（替代like，更高效）

        List<CarNumPrefix> list = carNumPrefixMapper.selectList(queryWrapper);
        if (list.size() > 1) {
            //throw new BusinessException("存在多个车身号前缀，请联系管理员"); // 用自定义异常统一处理
            //返回第一个
            return list.get(0);
//            return null;
        }else {
            return list.isEmpty() ? null : list.get(0);
        }
    }

    /**
     * 处理已存在的前缀（更新逻辑）
     */
    private Result handleExistingPrefix(CarNumPre carNumPre, CarNumPrefix existingPrefix, WorkingPosition workingPosition) {
        String newCarNumPre = carNumPre.getCarNumPre();
        // 若传入新前缀，则更新
        if (!StringUtils.isBlank(newCarNumPre)) {//StringUtils.hasText(newCarNumPre)
            existingPrefix.setCarNum(newCarNumPre);
            carNumPrefixMapper.updateById(existingPrefix);
            extracted(carNumPre, existingPrefix); // 复用公共逻辑
            return new Result(Code.SAVE_OK, "工位<" + workingPosition.getWorkingPositionName() + ">的车身号前缀已更新");
        } else {
            // 未传入新前缀，返回已存在提示
            return new Result(Code.SAVE_OK, "工位" + carNumPre.getWorkingPositionId() + "的车身号前缀已设置");
        }
    }

    /**
     * 处理不存在的前缀（新增逻辑）
     */
    private Result handleNonExistingPrefix(CarNumPre carNumPre, Long workingPositionId,
                                           CarNumPrefix yesterdayPrefix, WorkingPosition workingPosition) {
        CarNumPrefix newPrefix = new CarNumPrefix();
        newPrefix.setWorkingPositionId(workingPositionId);
        newPrefix.setCreateTime(new Date());

        // 1. 若传入新前缀，直接使用
        String newCarNumPre = carNumPre.getCarNumPre();
        if (!StringUtils.isBlank(newCarNumPre)) {//StringUtils.hasText(newCarNumPre)
            newPrefix.setCarNum(newCarNumPre);
            carNumPrefixMapper.insert(newPrefix);
            extracted(carNumPre, newPrefix);
            return new Result(Code.SAVE_OK, "<" + workingPosition.getWorkingPositionName() + ">车身号前缀设置成功");
        }

        // 2. 未传入新前缀，复用昨日数据
        if (yesterdayPrefix != null) {
            newPrefix.setCarNum(yesterdayPrefix.getCarNum());
            carNumPrefixMapper.insert(newPrefix);
            extracted(carNumPre, newPrefix);
            return new Result(Code.SAVE_OK, "继续使用昨天的车身号前缀");
        }

        // 3. 无昨日数据且未传入新前缀，返回错误
        return new Result(Code.SAVE_ERR, "请输入车身号前缀");
    }

    //优化前：
//    @PostMapping("/sendCarNumPrefix")
//    @Transactional
//    @CrossOrigin
//    public Result sendCarNumPrefix(@RequestHeader("Authorization") String Token,
//                                   @RequestBody CarNumPre carNumPre) {
//        //System.out.println("carNumPre是"+carNumPre);
//        // 验证令牌
//        if (!isValidToken(Token)) {
//            return new Result(Code.LOGIN_ERR, "无效或过期的令牌");
//        }
//
//        WorkingPosition workingPosition = workingPositionService.getById(carNumPre.getWorkingPositionId());
//
//        LocalDate today = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String todayStr = today.format(formatter);
//
//        LocalDate yesterday = today.minusDays(1);
//        String yesterdayStr = yesterday.format(formatter);
//
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(CarNumPrefix::getCreateTime, todayStr);
//        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, carNumPre.getWorkingPositionId());
//        int count = carNumPrefixMapper.selectCount(queryWrapper);
//        if (count == 1) {
//            if(carNumPre.getCarNumPre() != null && !carNumPre.getCarNumPre().isEmpty()) {
//                CarNumPrefix carNumPrefix = carNumPrefixMapper.selectOne(queryWrapper);
//                carNumPrefix.setCarNum(carNumPre.getCarNumPre());
//                carNumPrefixMapper.updateById(carNumPrefix);
//
//                extracted(carNumPre, carNumPrefix);
//
//                return new Result(Code.SAVE_OK,
//                        "工位<"+workingPosition.getWorkingPositionName()+">的车身号前缀已更新");
//            }
//        } else if (count > 1) {
//            log.info("数据库存在多个车身号前缀");
//            return new Result(Code.SAVE_ERR, "存在多个车身号前缀，请联系管理员");
//        }
//
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper0 = new LambdaQueryWrapper<>();
//        queryWrapper0.like(CarNumPrefix::getCreateTime, todayStr);
//        queryWrapper0.eq(CarNumPrefix::getWorkingPositionId, carNumPre.getWorkingPositionId());
//        int count0 = carNumPrefixMapper.selectCount(queryWrapper);
//        if (count0 > 0) {
//            return new Result(Code.SAVE_OK,
//                    "工位"+carNumPre.getWorkingPositionId()+"的车身号前缀已设置");
//        }
//
//        //System.out.println("CarNumPre是:"+carNumPre.getCarNumPre());
//        CarNumPrefix carNumPrefix = new CarNumPrefix();
//        if(carNumPre.getCarNumPre() != null && !carNumPre.getCarNumPre().isEmpty()) {
//            //System.out.println("CarNumPre.size()是"+carNumPre.getCarNumPre().length());
//            carNumPrefix.setCarNum(carNumPre.getCarNumPre());
//        }else {
//            LambdaQueryWrapper<CarNumPrefix> queryWrapperYes = new LambdaQueryWrapper<>();
//            queryWrapperYes.like(CarNumPrefix::getCreateTime, yesterdayStr);
//            queryWrapperYes.eq(CarNumPrefix::getWorkingPositionId, carNumPre.getWorkingPositionId());
//            int count1 = carNumPrefixMapper.selectCount(queryWrapperYes);
//            CarNumPrefix carNumPrefix0 = null;
//            if (count1 == 1) {
//                carNumPrefix0 = carNumPrefixMapper.selectOne(queryWrapperYes);
//            }else if (count1 > 1) {
//                log.info("存在多个车身号前缀");
//                return new Result(Code.SAVE_ERR, "存在多个车身号前缀，请联系管理员");
//            }
//            if (carNumPrefix0 != null) {
//                carNumPrefix.setCarNum(carNumPrefix0.getCarNum());
//                carNumPrefix.setCreateTime(new Date());
//                carNumPrefix.setWorkingPositionId(Long.valueOf(carNumPre.getWorkingPositionId()));
//                carNumPrefixMapper.insert(carNumPrefix);
//
//                extracted(carNumPre, carNumPrefix);
////                //查询当前工位是哪辆车，实时修改当前读到的车型的车身号前缀
////                String carNum = null;
////                String carType = null;
////                String repeat = null;
////                if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition1.toString())){
////                    carNum = (String) CacheUtil.getFromCache("carNum1");
////                    carType = (String) CacheUtil.getFromCache("carType1");
////                    repeat = (String) CacheUtil.getFromCache("repeat1");
////                }else if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition2.toString())){
////                    carNum = (String) CacheUtil.getFromCache("carNum2");
////                    carType = (String) CacheUtil.getFromCache("carType2");
////                    repeat = (String) CacheUtil.getFromCache("repeat2");
////                }
////                LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
////                queryCarWrapper.eq(Car::getCarId, carNum);
////                queryCarWrapper.eq(Car::getCarType, carType);
////                queryCarWrapper.eq(Car::getRepeatNum, repeat);
////                Integer count2 = carMapper.selectCount(queryCarWrapper);
////                if (count2 == 1) {
////                    Car car = carMapper.selectOne(queryCarWrapper);
////                    car.setCarId(carNumPrefix.getCarNum()+repeat);
////                    carMapper.updateById(car);
////                }
//
//                return new Result(Code.SAVE_OK, "继续使用昨天的车身号前缀");
//            } else {
//                return new Result(Code.SAVE_ERR, "请输入车身号前缀");
//            }
//        }
//        //count == 0时添加
//        carNumPrefix.setWorkingPositionId(Long.valueOf(carNumPre.getWorkingPositionId()));
//        carNumPrefix.setCreateTime(new Date());
//        carNumPrefixMapper.insert(carNumPrefix);
//
//
//        extracted(carNumPre, carNumPrefix);
//        //查询当前工位是哪辆车，实时修改当前读到的车型的车身号前缀
////        String carNum = null;
////        String carType = null;
////        String repeat = null;
////        if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition1.toString())){
////            carNum = (String) CacheUtil.getFromCache("carNum1");
////            carType = (String) CacheUtil.getFromCache("carType1");
////            repeat = (String) CacheUtil.getFromCache("repeat1");
////        }else if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition2.toString())){
////            carNum = (String) CacheUtil.getFromCache("carNum2");
////            carType = (String) CacheUtil.getFromCache("carType2");
////            repeat = (String) CacheUtil.getFromCache("repeat2");
////        }
////        LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
////        queryCarWrapper.eq(Car::getCarId, carNum);
////        queryCarWrapper.eq(Car::getCarType, carType);
////        queryCarWrapper.eq(Car::getRepeatNum, repeat);
////        Integer count1 = carMapper.selectCount(queryCarWrapper);
////        if (count1 == 1) {
////            Car car = carMapper.selectOne(queryCarWrapper);
////            car.setCarId(carNumPrefix.getCarNum()+repeat);
////            carMapper.updateById(car);
////        }
//
//        return new Result(Code.SAVE_OK, "<"+workingPosition.getWorkingPositionName()+">车身号前缀设置成功");
//    }

    //优化后：
    private void extracted(CarNumPre carNumPre, CarNumPrefix carNumPrefix) {
        // 1. 统一获取工位标识（避免重复调用）
        String positionId = carNumPre.getWorkingPositionId();

        // 2. 通过映射关系获取缓存键（消除冗长的if-else）
        CacheKeyInfo cacheKeyInfo = getCacheKeyInfo(positionId);
        if (cacheKeyInfo == null) {
            log.warn("未配置的工位ID: {}", positionId);
            return; // 无效工位直接返回，避免后续空指针
        }

        // 3. 一次性获取缓存数据（减少重复代码）
        String carNum = getTrimmedCacheValue(cacheKeyInfo.carNumKey);
        String carType = getTrimmedCacheValue(cacheKeyInfo.carTypeKey);
        String repeat = getTrimmedCacheValue(cacheKeyInfo.repeatKey);

        // 4. 构建查询条件（提前校验空值，避免无效查询）
        if (StringUtils.isBlank(carNum) || StringUtils.isBlank(carType) || StringUtils.isBlank(repeat)) {
            log.info("缓存数据不完整，跳过处理: carNum={}, carType={}, repeat={}", carNum, carType, repeat);
            return;
        }

        LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
        queryCarWrapper.eq(Car::getCarId, carNum)
                .eq(Car::getCarType, carType)
                .eq(Car::getRepeatNum, repeat);

        // 5. 处理查询结果（合并缓存更新逻辑）
        int count = carMapper.selectCount(queryCarWrapper);
        String newCarId = carNumPrefix.getCarNum() + repeat;

        //更新前的缓存：
//        Object a = CacheUtil.getFromCache(cacheKeyInfo.carNumKey);
//        System.out.println("更新前的缓存a="+a);

        // 先更新缓存（无论新增还是更新，缓存逻辑一致）
        CacheUtil.putInCache(cacheKeyInfo.carNumKey, newCarId);

        //更新后的缓存：
//        Object b = CacheUtil.getFromCache(cacheKeyInfo.carNumKey);
//        System.out.println("更新后的缓存b="+b);


        // 6. 校验车型和车身号合法性（抽取为工具方法）
        if (!isValidCarInfo(carType, newCarId)) {
            log.info("车型或车身号无效，跳过数据库操作: carType={}, newCarId={}", carType, newCarId);
            return;
        }

        // 7. 数据库操作（区分新增和更新）
        if (count == 1) {
            Car car = carMapper.selectOne(queryCarWrapper);
            car.setCarId(newCarId);
            carMapper.updateById(car);
        } else if (count == 0) {
            Car car = new Car();
            car.setCarId(newCarId);
            car.setWorkingPositionId(Long.valueOf(positionId));
            car.setCarType(carType);
            car.setRepeatNum(repeat);
            carMapper.insert(car);
        }
    }

    // 辅助类：封装缓存键信息
    private static class CacheKeyInfo {
        String carNumKey;
        String carTypeKey;
        String repeatKey;

        CacheKeyInfo(String carNumKey, String carTypeKey, String repeatKey) {
            this.carNumKey = carNumKey;
            this.carTypeKey = carTypeKey;
            this.repeatKey = repeatKey;
        }
    }

    // 获取缓存键映射（消除冗长的if-else）
    private CacheKeyInfo getCacheKeyInfo(String positionId) {
        String pos1 = MessageConstant.workingPosition1.toString();
        String pos2 = MessageConstant.workingPosition2.toString();

        if (pos1.equals(positionId)) {
            return new CacheKeyInfo("carNum1", "carType1", "repeat1");
        } else if (pos2.equals(positionId)) {
            return new CacheKeyInfo("carNum2", "carType2", "repeat2");
        }
        return null; // 支持扩展更多工位
    }

    // 获取缓存并自动去除首尾空格
    private String getTrimmedCacheValue(String cacheKey) {
        Object value = CacheUtil.getFromCache(cacheKey);
        return value instanceof String ? ((String) value).trim() : null;
    }

    // 校验车型和车身号合法性
    private boolean isValidCarInfo(String carType, String carId) {
        return !"未知车型".equals(carType) && !carId.contains("null");
    }


    //优化前：
    //查询当前工位是哪辆车，实时修改当前读到的车型的车身号前缀
//    private void extracted(CarNumPre carNumPre, CarNumPrefix carNumPrefix) {
//
//        String carNum = null;
//        String carType = null;
//        String repeat = null;
//        if (carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition1.toString())) {
//            carNum = (String) CacheUtil.getFromCache("carNum1");
//            carType = (String) CacheUtil.getFromCache("carType1");
//            repeat = (String) CacheUtil.getFromCache("repeat1");
//        } else if (carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition2.toString())) {
//            carNum = (String) CacheUtil.getFromCache("carNum2");
//            carType = (String) CacheUtil.getFromCache("carType2");
//            repeat = (String) CacheUtil.getFromCache("repeat2");
//        }
//        if (carNum != null){
//            carNum = carNum.trim();
//        }
//        if (carType != null){
//            carType = carType.trim();
//        }
//        if (repeat != null){
//            repeat = repeat.trim();
//        }
//        LambdaQueryWrapper<Car> queryCarWrapper = new LambdaQueryWrapper<>();
//        queryCarWrapper.eq(Car::getCarId, carNum);
//        queryCarWrapper.eq(Car::getCarType, carType);
//        queryCarWrapper.eq(Car::getRepeatNum, repeat);
//        Integer count1 = carMapper.selectCount(queryCarWrapper);
//        if (count1 == 1) {
//            Car car = carMapper.selectOne(queryCarWrapper);
//            car.setCarId(carNumPrefix.getCarNum()+repeat);
//
//            //数据库更新成功之前，需要先更新车身号的缓存，否则会在数据库存一条
//            if (carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition1.toString())) {
//                CacheUtil.putInCache("carNum1", carNumPrefix.getCarNum() + repeat);
//            } else if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition2.toString())) {
//                CacheUtil.putInCache("carNum2", carNumPrefix.getCarNum() + repeat);
//            }
//            if(!car.getCarType().equals("未知车型") &&
//                    !car.getCarId().contains("null")) {
//                carMapper.updateById(car);
//            }
//        } else if (count1 == 0) {//说明未存进数据库，所以拼接后修改缓存让它能够进入数据库
//            if (carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition1.toString())) {
//                CacheUtil.putInCache("carNum1", carNumPrefix.getCarNum() + repeat);
//            } else if(carNumPre.getWorkingPositionId().equals(MessageConstant.workingPosition2.toString())) {
//                CacheUtil.putInCache("carNum2", carNumPrefix.getCarNum() + repeat);
//            }
//            Car car = new Car();
//            car.setCarId(carNumPrefix.getCarNum()+repeat);
//            car.setWorkingPositionId(Long.valueOf(carNumPre.getWorkingPositionId()));
//            car.setCarType(carType);
//            car.setRepeatNum(repeat);
//            if(!car.getCarType().equals("未知车型") &&
//                    !car.getCarId().contains("null")) {
//                carMapper.insert(car);
//            }
//        }
//    }

    //优化后：
//    @GetMapping("/checkCarNumPrefixExist1")
//    @CrossOrigin
//    @Async("ioIntensiveThreadPool") // 使用IO密集型线程池
//    public CompletableFuture<Result> checkCarNumPrefixExist1() {
//        log.info("checkCarNumPrefixExist1的线程id: {}", Thread.currentThread().getId() + "名" + Thread.currentThread().getName());
//
//        return CompletableFuture.supplyAsync(() -> {
//            LocalDate today = LocalDate.now();
//            String todayStr = today.format(DateTimeFormatter.ISO_LOCAL_DATE); // 使用标准格式
//
//            // 构建查询条件
//            LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper
//                    .apply("DATE_FORMAT(create_time, '%Y-%m-%d') = {0}", todayStr) // 精确匹配日期部分
//                    .eq(CarNumPrefix::getWorkingPositionId, MessageConstant.workingPosition1);
//
//            try {
//                // 执行查询并处理结果
//                List<CarNumPrefix> carNumPrefixes = carNumPrefixMapper.selectList(queryWrapper);
//                int count = carNumPrefixes.size();
//
//                if (count == 1) {
//                    log.info("今日已生成车号前缀");
//                    return new Result(1, carNumPrefixes.get(0).getCarNum(), "门铰链工位的车身号前缀已设置");
//                } else if (count > 1) {
//                    log.error("数据库存在多个车号前缀: {}", count);
//                    return new Result(2, "门铰链工位存在多个车号前缀");
//                } else {
//                    log.info("今日未生成车号前缀");
//                    return new Result(0, "门铰链工位未设置车身号前缀");
//                }
//            } catch (Exception e) {
//                log.error("查询车号前缀异常", e);
//                return new Result(500, "系统异常，请稍后重试");
//            }
//        });
//    }

    //优化前：
//    @GetMapping("/checkCarNumPrefixExist1")
//    @CrossOrigin
//    public Result checkCarNumPrefixExist1() {
//        log.info("checkCarNumPrefixExist1的线程id:{}", Thread.currentThread().getId()+"名"+Thread.currentThread().getName());
//
//        LocalDate today = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String todayStr = today.format(formatter);
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(CarNumPrefix::getCreateTime, todayStr);
//        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, MessageConstant.workingPosition1);
////        //System.out.println("今天是"+todayStr);
//        int count = carNumPrefixMapper.selectCount(queryWrapper);
////        //System.out.println("carNumPrefixMapperCount是"+count);
//        if (count == 1) {
//            log.info("今日已生成车号前缀");
//            CarNumPrefix carNumPrefix = carNumPrefixMapper.selectOne(queryWrapper);
//            return new Result(1,carNumPrefix.getCarNum(), "门铰链工位的车身号前缀已设置");
//        } else if (count > 1) {
//            log.info("数据库存在多个车号前缀");
//            return new Result(2, "门铰链工位存在多个车号前缀");
//        } else {
//            log.info("今日未生成车号前缀");
//            return new Result(0, "门铰链工位未设置车身号前缀");
//        }
//
//    }


    //优化后：
    // 获取线程池的方法（替代@Async注解，提高灵活性）
//    @GetMapping("/checkCarNumPrefixExist2")
//    @CrossOrigin
//    @Async("ioIntensiveThreadPool") // 使用IO密集型线程池
//    public CompletableFuture<Result> checkCarNumPrefixExist2() {
//        log.info("checkCarNumPrefixExist2的线程id: {}", Thread.currentThread().getId() + "名" + Thread.currentThread().getName());
//
//        LocalDate today = LocalDate.now();
//        String todayStr = today.format(DateTimeFormatter.ISO_LOCAL_DATE);
//
//        // 构建查询条件（优化日期查询）
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.apply("DATE(create_time) = {0}", todayStr)
//                .eq(CarNumPrefix::getWorkingPositionId, MessageConstant.workingPosition2);
//
//        try {
//            // 单次查询获取列表
//            List<CarNumPrefix> carNumPrefixes = carNumPrefixMapper.selectList(queryWrapper);
//            int count = carNumPrefixes.size();
//
//            if (count == 1) {
//                log.info("发动机盖工位今日已生成车号前缀");
//                return CompletableFuture.completedFuture(
//                        new Result(1, carNumPrefixes.get(0).getCarNum(), "发动机盖工位的车身号前缀已设置"));
//            } else if (count > 1) {
//                log.error("发动机盖工位存在多个车号前缀: {}", count);
//                return CompletableFuture.completedFuture(
//                        new Result(2, "发动机盖工位存在多个车号前缀"));
//            } else {
//                log.info("发动机盖工位今日未生成车号前缀");
//                return CompletableFuture.completedFuture(
//                        new Result(0, "发动机盖工位未设置车身号前缀"));
//            }
//        } catch (Exception e) {
//            log.error("查询发动机盖工位车号前缀异常", e);
//            return CompletableFuture.completedFuture(
//                    new Result(500, "系统异常，请稍后重试"));
//        }
//    }


    //优化前：
//    @GetMapping("/checkCarNumPrefixExist2")
//    @CrossOrigin
//    public Result checkCarNumPrefixExist2() {
//        log.info("checkCarNumPrefixExist2的线程id:{}", Thread.currentThread().getId()+"名"+Thread.currentThread().getName());
//
//        LocalDate today = LocalDate.now();
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String todayStr = today.format(formatter);
//        LambdaQueryWrapper<CarNumPrefix> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(CarNumPrefix::getCreateTime, todayStr);
//        queryWrapper.eq(CarNumPrefix::getWorkingPositionId, MessageConstant.workingPosition2);
////        //System.out.println("今天是"+todayStr);
//        int count = carNumPrefixMapper.selectCount(queryWrapper);
////        //System.out.println("carNumPrefixMapperCount是"+count);
//        if (count == 1) {
//            log.info("今日已生成车号前缀");
//            CarNumPrefix carNumPrefix = carNumPrefixMapper.selectOne(queryWrapper);
//            return new Result(1,carNumPrefix.getCarNum(), "发动机盖工位的车身号前缀已设置");
//        } else if (count > 1) {
//            log.info("数据库存在多个车号前缀");
//            return new Result(2, "发动机盖工位存在多个车号前缀");
//        } else {
//            log.info("今日未生成车号前缀");
//            return new Result(0, "发动机盖工位未设置车身号前缀");
//        }
//
//    }

    private boolean isValidToken(String token) {
//        log.info("token是"+token);
        if (token == null || !token.startsWith("Bearer ")) {
            return false; // 检查令牌格式
        }
        // 提取实际的JWT部分
        token = token.substring(7); // 去掉“Bearer ”前缀
        log.info("token1是"+token);
        try {
            log.info("解析令牌");
            // 解析令牌
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .setAllowedClockSkewSeconds(300) // 允许5分钟的时钟偏差
                    .parseClaimsJws(token)
                    .getBody();

            // 获取过期时间
            Date expiration = claims.getExpiration();
            log.info("过期时间："+expiration);
            // 检查是否过期
            return expiration != null && expiration.after(new Date());
        } catch (ExpiredJwtException e) {
            // 处理过期令牌的异常
            log.info("令牌已过期: " + e.getMessage());
            return false;
        } catch (SignatureException e) {
            // 处理签名验证失败的异常
            log.info("令牌签名无效: " + e.getMessage());
            return false;
        } catch (Exception e) {
            // 处理其他可能的异常
            log.info("令牌验证失败: " + e.getMessage());
            return false;
        }
    }


    @GetMapping("/exportToExcel")
    @CrossOrigin
    public ResponseEntity<byte[]> exportToExcel() {
        try {
            Map<String, Object> map = carService.exportToExcel();
            byte[] excelBytes1 = (byte[]) map.get("excel1");
            byte[] excelBytes2 = (byte[]) map.get("excel2");

            String excel1Name = (map.get("excel1Name") != null) ? (String) map.get("excel1Name") : MessageConstant.camryFileName;
            String excel2Name = (map.get("excel2Name") != null) ? (String) map.get("excel2Name") : MessageConstant.levinFileName;

//            String excel1Name = MessageConstant.camryFileName;//(String) map.get("excel1Name");
//            String excel2Name = MessageConstant.levinFileName;//(String) map.get("excel2Name");

            // 创建ZIP输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(baos);

            LocalDate today = LocalDate.now();
            YearMonth currentYearMonth = YearMonth.from(today);
            YearMonth previousYearMonth = currentYearMonth.minusMonths(1);
            log.info("前一个月是："+previousYearMonth);
            String month = previousYearMonth.toString();

            excel1Name = "(" + month + ")" + excel1Name;
            // 添加第一个文件到ZIP
            ZipEntry zipEntry1 = new ZipEntry(excel1Name);
            zipOutputStream.putNextEntry(zipEntry1);
            zipOutputStream.write(excelBytes1);
            zipOutputStream.closeEntry();

            excel2Name = "(" + month + ")" + excel2Name;
            // 添加第二个文件到ZIP
            ZipEntry zipEntry2 = new ZipEntry(excel2Name);
            zipOutputStream.putNextEntry(zipEntry2);
            zipOutputStream.write(excelBytes2);
            zipOutputStream.closeEntry();

            // 关闭ZIP输出流
            zipOutputStream.close();
            byte[] zipBytes = baos.toByteArray();

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/zip"));
            headers.setContentDispositionFormData("attachment", "exports.zip");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(zipBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


//    @GetMapping("/exportToExcel")
//    @CrossOrigin//ResponseEntity<byte[]>
//    public Map exportToExcel(){
//        try {
//            Map map = carService.exportToExcel();
//            byte[] excelBytes1 = (byte[]) map.get("excel1");
//            byte[] excelBytes2 = (byte[]) map.get("excel2");
//
////            byte[] excelBytes = carService.exportToExcel();
//
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
//            headers.setContentDispositionFormData("attachment", "采样表.xlsx");
////            headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
////            headers.setContentDispositionFormData("attachment", "采样表.xlsx");
//
//            Map map0 = new HashMap<>();
//            map0.put("excel1", ResponseEntity.ok()
//                    .headers(headers)
//                    .body(excelBytes1));
//            map0.put("excel1Name", map.get("excel1Name"));
//            map0.put("excel2", ResponseEntity.ok()
//                    .headers(headers)
//                    .body(excelBytes2));
//            map0.put("excel2Name", map.get("excel2Name"));
//            return map0;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
////            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
//        }
//    }

    @GetMapping("/deleteCarData")
    @Transactional
    @CrossOrigin
    public Result deleteCarData(@RequestHeader("Authorization") String Token,
             // 从请求头获取令牌
            @RequestParam String carId) {//@Validated
        log.info("删除车辆信息：{}", carId);
//        //System.out.println("删除车辆信息："+ carId);
        // 验证令牌
        if (!isValidToken(Token)) {
            return new Result(Code.LOGIN_ERR, "无效或过期的令牌");
        }


        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set<ConstraintViolation<String>> violations = validator.validate(carId);

        if (!violations.isEmpty()) {
            StringBuilder errorMessage = new StringBuilder();
            for (ConstraintViolation<String> violation : violations) {
                errorMessage.append(violation.getMessage()).append("; ");
            }
            return new Result(Code.UPDATE_ERR, errorMessage.toString());
        }

        Car car = carService.getById(carId);
        if (car == null) {
            return new Result(Code.UPDATE_ERR, "该车辆不存在");
        }
        //根据车辆删除螺丝和告警数据
        LambdaQueryWrapper<CarStatus> carStatusLambdaQueryWrapper = new LambdaQueryWrapper<>();
        carStatusLambdaQueryWrapper.eq(CarStatus::getCarId, carId);
        boolean x = carStatusService.remove(carStatusLambdaQueryWrapper);
        LambdaQueryWrapper<Screw> screwLambdaQueryWrapper = new LambdaQueryWrapper<>();
        screwLambdaQueryWrapper.eq(Screw::getCarId, carId);
        boolean y = screwService.remove(screwLambdaQueryWrapper);

//        boolean i = false;
        boolean i = carService.removeById(car.getId());

        if (i) {
            return new Result(Code.DELETE_OK,"车辆相关信息删除成功");
        } else {
            return new Result(Code.DELETE_ERR, "车辆信息删除失败");
        }
    }

}
